<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal, z } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { roleAddApi, roleEditApi, roleQueryByIdApi } from '#/api/system/role';
import { queryDictOptionsApi } from '#/utils';
import { asyncValidDataApi } from '#/utils/handle/async-rules';

const record = ref({});
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入角色名称',
      },
      fieldName: 'roleName',
      label: '角色名称',
      rules: z.string().max(30, '角色名称最多30个字符'),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入角色编码',
      },
      dependencies: {
        disabled(values) {
          return !!values.id;
        },
        // 实现异步API校验
        rules(values, formApi) {
          const rowId = formApi.values?.id;
          return asyncValidDataApi(
            z
              .string({ required_error: '请输入角色编码' })
              .trim()
              .min(3, '角色编码至少3个字符')
              .max(30, '角色编码最多30个字符'),
            {
              tableName: 'sys_role',
              fieldName: 'role_code',
              rowId,
            },
          );
        },
        triggerFields: ['id', 'roleCode'],
      },
      fieldName: 'roleCode',
      label: '角色编码',
      rules: z.string().max(30, '角色编码最多30个字符'),
    },
    {
      component: 'ApiRadioGroup',
      defaultValue: 0,
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'status',
        },
      },
      fieldName: 'status',
      label: '状态',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入排序',
      },
      fieldName: 'sortRank',
      label: '排序',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
      },
      formItemClass: 'col-span-2',
      fieldName: 'remark',
      label: '备注',
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  title: '角色',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      modalApi.setState({ title: `${record.value.id ? '编辑' : '新增'}角色` });
      if (record.value.id) {
        initFun();
      }
    }
  },
});
async function initFun() {
  const res = await roleQueryByIdApi({ id: record.value.id });
  await formApi.setValues(res, false);
}
async function onSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    if (record.value.id) {
      const msg = await roleEditApi(values);
      message.success(msg);
      await modalApi.close();
    } else {
      const msg = await roleAddApi(values);
      message.success(msg);
      await modalApi.close();
    }
  }
}
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
